package com.bosssoft.hr.jobmonitor.core.job;

import com.bosssoft.hr.jobmonitor.core.file.FileTool;
import com.bosssoft.hr.jobmonitor.entity.Task;
import com.bosssoft.hr.jobmonitor.util.XmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

/***
 * @Author lys(cherish)
 * @Description 作业任务工具
 * @Date  2019/2/26
 **/
@Component
public class TaskTool {

    //文件工具注入
    @Autowired
    private FileTool fileTool;

    /**
     * 获取所有的作业任务
     * @return
     */
    public List<Task> getAllTask() {
        String xmlStr = fileTool.readFile("resource"+File.separator+"job"+File.separator+"task.xml");
        List<Task> taskList = XmlUtil.toBean(xmlStr, List.class);
        return taskList;
    }


    /***
     * @Author lys(cherish)
     * @Description 获取最近的作业任务
     * @Date  2019/2/26
     * @Param []
     * @return com.bosssoft.hr.jobmonitor.entity.Task
     **/
    public Task getLastTask(){
        List<Task> allTask = getAllTask();
        TreeSet<Task> tasks = new TreeSet<>(allTask);
        Task last = tasks.last();
        return last;
    }

    /***
     * @Author lys(cherish)
     * @Description 添加一件任务
     * @Date  2019/2/26
     * @Param [task] 任务
     * @return void
     **/
    public void saveTask(Task task){
        List<Task> allTask = getAllTask();
        if(allTask==null){
            allTask = new ArrayList<Task>();
        }
        allTask.add(task);
        String newXmlStr = XmlUtil.toXml(allTask);
        fileTool.writeFile( "resource"+File.separator+"job"+File.separator+"task.xml",newXmlStr);
    }
}
